package com.xbongbong.pro.aiassistant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.pojo.UserSimpPojo;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.aiassistant.service.SsMessageMergeService;
import com.xbongbong.pro.domain.entity.AiAssistantEntity;
import com.xbongbong.pro.domain.entity.AiAssistantHistoryEntity;
import com.xbongbong.pro.enums.smartsettings.enums.SmartActionTypeEnum;
import com.xbongbong.pro.smartsettings.pojo.SsExecutorPojo;
import com.xbongbong.pro.smartsettings.pojo.SsMessageMergePojo;
import com.xbongbong.pro.smartsettings.pojo.SsTimeAndExecutorPojo;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartStrategyRabbitMqDTO;
import com.xbongbong.saas.constant.StringConstant;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @description: 智能助手--消息聚合
 * @Author: hongxiao
 * @date: 2019-05-14 21:21
 * @since v1.0
 */
@Service("ssMessageMergeService")
public class SsMessageMergeServiceImpl implements SsMessageMergeService {

    @Override
    public List<SsMessageMergePojo> getMessageMerge(SmartStrategyRabbitMqDTO rabbitMqDTO, List<SsExecutorPojo> excutorList) {

        // 执行动作为消息的智能助手
        List<Long> messageSmartIdList = new ArrayList<>();
        rabbitMqDTO.getList().forEach(item -> {
            if(SmartActionTypeEnum.MESSAGE.getCode().equals(item.getAction())) {
                messageSmartIdList.add(item.getId());
            }
        });

        // smartId-formId对应的执行人数据
        Map<String, List<SsExecutorPojo>> smartFormPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // smartId-formId对应的执行人
        Map<String, Set<String>> smartFormExecutorMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for(SsExecutorPojo pojo : excutorList) {
            Long smartId = pojo.getSmartSettingsId();
            if(!messageSmartIdList.contains(smartId)) {
                continue;
            }

            Long formId = pojo.getFormId();
            String key = getCustomKey(smartId.toString(), formId.toString());

            if(smartFormPojoMap.containsKey(key)) {
                smartFormPojoMap.get(key).add(pojo);
                smartFormExecutorMap.get(key).addAll(pojo.getExecutorIdList());
            } else {
                List<SsExecutorPojo> list = new ArrayList<>();
                list.add(pojo);
                smartFormPojoMap.put(key, list);
                Set<String> userIdSet = new HashSet<>();
                userIdSet.addAll(pojo.getExecutorIdList());
                smartFormExecutorMap.put(key, userIdSet);
            }
        }

        // 执行人对应的数据
        Map<String, List<Long>> smartFormUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        smartFormPojoMap.forEach((key, list) ->{
            Set<String> userIdSet = smartFormExecutorMap.get(key);
            userIdSet.forEach(userId -> {
                String newKey = getCustomKey(key, userId);
                list.forEach(item -> {
                    // 数据中有执行人
                    if(item.getExecutorIdList().contains(userId)) {
                        // 聚合数据到对应的执行人下面
                        if(smartFormUserMap.containsKey(newKey)) {
                            smartFormUserMap.get(newKey).add(item.getDataId());
                        } else {
                            List<Long> dataIds = new ArrayList<>();
                            dataIds.add(item.getDataId());
                            smartFormUserMap.put(newKey, dataIds);
                        }
                    }
                });
            });
        });

        List<SsMessageMergePojo> resultList = new ArrayList<>();
        smartFormUserMap.forEach((key, dataIds) ->{
            List<String> keys = splitCustomKey(key);
            Long smartId = Long.parseLong(keys.get(0));
            Long formId = Long.parseLong(keys.get(1));
            String userId = keys.get(2);

            SsMessageMergePojo pojo = new SsMessageMergePojo();
            pojo.setSmartSettingsId(smartId);
            pojo.setFormId(formId);
            pojo.setExcutorId(userId);
            pojo.setDataIdList(dataIds);

            resultList.add(pojo);
        });

        return resultList;
    }

    @Override
    public List<SsMessageMergePojo> getMessageMergeList(List<SsExecutorPojo> executorList, AiAssistantEntity aiAssistantEntity, List<AiAssistantHistoryEntity> addList, List<AiAssistantHistoryEntity> updateList) {
        List<SsMessageMergePojo> ssMessageMergeList = new ArrayList<>();
        Set<String> userIdSet = new HashSet<>();
        if (CollectionsUtil.isEmpty(executorList)) {
            return ssMessageMergeList;
        }
        if (CollectionsUtil.isEmpty(executorList) && CollectionsUtil.isEmpty(addList) && CollectionsUtil.isEmpty(updateList)) {
            return ssMessageMergeList;
        }
        Map<Long, List<SsTimeAndExecutorPojo>> executorMap = new HashMap<>(executorList.size());
        long now = DateTimeUtil.getInt();
        executorList.forEach(item->{
            userIdSet.addAll(item.getExecutorIdList());
            List<SsTimeAndExecutorPojo> ssTimeAndExecutorPojos = new ArrayList<>();
            if (CollectionsUtil.isNotEmpty(item.getExecutorList())) {
                SsTimeAndExecutorPojo timeAndExecutorPojo = new SsTimeAndExecutorPojo();
                timeAndExecutorPojo.setTime(now);
                List<UserSimpPojo> userSimpPojoList = new ArrayList<>();
                item.getExecutorList().forEach(userEntity->{
                    UserSimpPojo userSimpPojo = new UserSimpPojo(userEntity.getUserId(), userEntity.getName(), userEntity.getAvatar());
                    userSimpPojoList.add(userSimpPojo);
                });
                timeAndExecutorPojo.setUsers(userSimpPojoList);
                ssTimeAndExecutorPojos.add(timeAndExecutorPojo);
            }
            executorMap.put(item.getDataId(), ssTimeAndExecutorPojos);
        });
        if (CollectionsUtil.isNotEmpty(addList)) {
            addList.forEach(item->{
                JSONArray jsonArray = new JSONArray();
                if (executorMap.containsKey(item.getDataId()) && CollectionsUtil.isNotEmpty(executorMap.get(item.getDataId()))) {
                   jsonArray = JSON.parseArray(JSON.toJSONString(executorMap.get(item.getDataId())));
                }
                item.setTimeAndExecutor(jsonArray);
            });
        }
        if (CollectionsUtil.isNotEmpty(updateList)) {
            updateList.forEach(item->{
                JSONArray jsonArray = item.getTimeAndExecutor();
                if (executorMap.containsKey(item.getDataId()) && CollectionsUtil.isNotEmpty(executorMap.get(item.getDataId()))) {
                    jsonArray.addAll(JSON.parseArray(JSON.toJSONString(executorMap.get(item.getDataId()))));
                }
                item.setTimeAndExecutor(jsonArray);
            });
        }

        Map<String, Set<Long>> smartFormUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userIdSet.forEach(userId -> {
            executorList.forEach(item -> {
                // 数据中有执行人
                if(item.getExecutorIdList().contains(userId)) {
                    // 聚合数据到对应的执行人下面
                    if(smartFormUserMap.containsKey(userId)) {
                        smartFormUserMap.get(userId).add(item.getDataId());
                    } else {
                        Set<Long> dataIds = new HashSet<>();
                        dataIds.add(item.getDataId());
                        smartFormUserMap.put(userId, dataIds);
                    }
                }
            });
        });
        Long smartId = aiAssistantEntity.getId();
        Long formId = aiAssistantEntity.getFormId();
        smartFormUserMap.forEach((userId, dataIds) ->{

            SsMessageMergePojo pojo = new SsMessageMergePojo();
            pojo.setSmartSettingsId(smartId);
            pojo.setFormId(formId);
            pojo.setExcutorId(userId);
            pojo.setDataIdList(new ArrayList<>(dataIds));

            ssMessageMergeList.add(pojo);
        });
        return ssMessageMergeList;
    }

    /**
     * 拼接map主键
     * @param key1 键1
     * @param key2 键2
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-15 20:34
     * @since v1.0
     * @version v1.0
     */
    private String getCustomKey(String key1, String key2) {
        return key1 + StringConstant.COMMA + key2;
    }

    /**
     * 分解map主键
     * @param key 键
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-15 20:36
     * @since v1.0
     * @version v1.0
     */
    private List<String> splitCustomKey(String key) {
        return StringUtil.toStringList(key, StringConstant.COMMA);
    }
}
